package com.cory.boot.config;

import javax.annotation.PostConstruct;
import javax.validation.Validator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J;
import com.cory.boot.component.uploader.UploaderConfig;

@Configuration
@PropertySource(value = {"classpath:application-boot.properties"})
public class BootMvcConfig implements WebMvcConfigurer {
    
    @PostConstruct
    public void init() {
        SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();
    }

    @Bean
    public Validator validator() {
        // 默认配置文件ValidationMessages.properties
        return new LocalValidatorFactoryBean();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 上传文件映射本地目录
        registry.addResourceHandler("/resource/**").addResourceLocations("file:" + UploaderConfig.resource + "/resource/");
    }
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/uploader/**").allowedOrigins("*").allowCredentials(true)
            .allowedMethods(new String[] { "GET", "POST", "PUT", "DELETE" }).maxAge(3600);
        registry.addMapping("/baidu/editor/**").allowedOrigins("*").allowCredentials(true)
                .allowedMethods(new String[] { "GET", "POST", "PUT", "DELETE" }).maxAge(3600);
    }
    
}
